package com.zdy.im.user.service.impl;


import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.ResultEnum;
import com.sixeco.framework.core.db.ext.Query;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.sixeco.framework.util.PageUtils;
import com.sixeco.framework.util.excel.ExcelUtils;
import com.zdy.im.chat.ChatMessageEnum;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.enums.ImResultCodeEnum;
import com.zdy.im.user.dao.ImMessageReadDao;
import com.zdy.im.user.dto.request.ImChatReadStatusRequestDto;
import com.zdy.im.user.dto.request.ImMessageReadRequestDto;
import com.zdy.im.user.entity.ImMessageRead;
import com.zdy.im.user.service.ImRoomChatMessageService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;


import com.zdy.im.user.entity.ImRoomChatMessage;
import com.zdy.im.user.dao.ImRoomChatMessageDao;
import com.zdy.im.user.dto.request.ImRoomChatMessageRequestDto;
import com.zdy.im.user.dto.response.ImRoomChatMessageResponseDto;
import java.io.InputStream;


/**
 * @ClassName: ImRoomChatMessageDao.java
 * @Description: 的数据交互处理类
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0.0
 * <p>
 * ----------------------------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 * ----------------------------------------------------------------------------
 * </p>
 */
@Service
public class ImRoomChatMessageServiceImpl  implements ImRoomChatMessageService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ImRoomChatMessageDao  imRoomChatMessageDao;

    @Autowired
    private ImMessageReadDao imMessageReadDao;


    /**
     * 保存同时更新数据库和缓存的实现方法
     * @param imRoomChatMessageRequestDto ImRoomChatMessageResponseDto
     * @return
     */
    @Override
    public ImRoomChatMessageResponseDto saveImRoomChatMessage(ImRoomChatMessageRequestDto imRoomChatMessageRequestDto){
        if(imRoomChatMessageRequestDto== null){
            return null;
        }
        ImRoomChatMessage imRoomChatMessage = ImRoomChatMessage.build().clone(imRoomChatMessageRequestDto);
        boolean result = imRoomChatMessageDao.save(imRoomChatMessage);
        if(!result){
            return null;
        }
        ImRoomChatMessageResponseDto imRoomChatMessageResponseDto = ImRoomChatMessageResponseDto.build().clone(imRoomChatMessage);
        return imRoomChatMessageResponseDto;


    }
    @Override
    public boolean saveBatchImRoomChatMessage(Collection<ImRoomChatMessageRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() !=  batchSize){
            return false;
        }
        List<ImRoomChatMessage> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImRoomChatMessage.build().clone(e)));
        boolean result = imRoomChatMessageDao.saveBatch(list,batchSize);
        return result;
    }

    @Override
    public boolean saveOrUpdateBatchImRoomChatMessage(Collection<ImRoomChatMessageRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<ImRoomChatMessage> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImRoomChatMessage.build().clone(e)));
        boolean result = imRoomChatMessageDao.saveOrUpdateBatch(list,batchSize);
        return result;
    }

    @Override
    public boolean updateBatchById(Collection<ImRoomChatMessageRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<ImRoomChatMessage> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImRoomChatMessage.build().clone(e)));
        boolean result =  imRoomChatMessageDao.updateBatchById(list,batchSize);
        return result;
    }

    /**
     * 更新同时更新数据库和缓存的实现方法
     * @param imRoomChatMessageRequestDto  ImRoomChatMessageResponseDto
     * @return
     */
    @Override
    public boolean updateImRoomChatMessage(ImRoomChatMessageRequestDto imRoomChatMessageRequestDto){

          if(null ==  imRoomChatMessageRequestDto){
              return false;
          }

        ImRoomChatMessage imRoomChatMessage = ImRoomChatMessage.build().clone(imRoomChatMessageRequestDto);

        return imRoomChatMessageDao.updateById(imRoomChatMessage);


    }



    /**
     * 更新消息的是否已读状态数据库和缓存的实现方法
     * @param statusRequestDto  ImChatReadStatusRequestDto
     * @return
     */
    @Override
    public boolean updateImChatMessageReadStatus(ImChatReadStatusRequestDto statusRequestDto){
        if(statusRequestDto == null || statusRequestDto.getMessageId() < 0 ){
            return false;
        }
        ImRoomChatMessage imChatMessage =  imRoomChatMessageDao.getById(statusRequestDto.getMessageId());
        if(imChatMessage == null){
            return false;
        }
        if(statusRequestDto.getSendUserId() != imChatMessage.getSendUserId()
                || statusRequestDto.getToUserId() != imChatMessage.getToId()){
            throw new SystemRuntimeException(ImResultCodeEnum.IM_MESSAGE_NOT_EXIST);
        }
        ChatMessageEnum messageEnum = ChatMessageEnum.getEnum( statusRequestDto.getReadType());
        imChatMessage.setReadStatus(messageEnum.getDbValue());
        imRoomChatMessageDao.updateById(imChatMessage);
        return true;
    }



    /**
     * 通过主键ID删除对象信息实现缓存和数据库,同时删除的方法
     * @param  idList
     * @return
     */
    @Override
    public int delImRoomChatMessageByIds(List<Long> idList){
        boolean result = false;
        if(null == idList){
            return ResultEnum.FAIL.id();
        }
        if( idList.size() == 1) {
            result = imRoomChatMessageDao.removeById(idList.get(0));
        }else {
            result =  imRoomChatMessageDao.removeByIds(idList);
        }
        if(result){
            return ResultEnum.SUCCESS.id();
        }
        return ResultEnum.FAIL.id();

    }


    /**
     * 通过主键ID更新对象实现缓存和数据库更新的方法
     * @param  imRoomChatMessageId
     * @return
     */
    @Override
    public ImRoomChatMessageResponseDto getImRoomChatMessageById(long imRoomChatMessageId){
        if(imRoomChatMessageId < 0 ){
            return null;
        }
        ImRoomChatMessage imRoomChatMessage =  imRoomChatMessageDao.getById(imRoomChatMessageId);
        if(imRoomChatMessage == null || imRoomChatMessage.getReadStatus() > 1){
            return null;
        }
        ImRoomChatMessageResponseDto imRoomChatMessageResponseDto = ImRoomChatMessageResponseDto.build().clone(imRoomChatMessage);

        return imRoomChatMessageResponseDto ;

    }

    @Override
    public List<ImRoomChatMessageResponseDto> getImRoomChatMessageByPage(BasePage page) {
        return null;
    }


    /**
    * 查询条件
    */

    public QueryWrapper<ImRoomChatMessage> checkQueryCondition(BasePage basePage) {
        QueryWrapper<ImRoomChatMessage> queryWrapper = new QueryWrapper<>();
        ImRoomChatMessageRequestDto imRoomChatMessageRequestDto = (ImRoomChatMessageRequestDto) basePage.getParamObject();

                                                                                                                                                                                                                                                                                                                                                return queryWrapper;
    }


    /**
     * 通过分页获取ImRoomChatMessage信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-12 17:26:21
     */

    public List<ImRoomChatMessageResponseDto> getImRoomChatMessageByPage(
            ResponseResultList<ImRoomChatMessageResponseDto> responseResultList, BasePage basePage){


        List<ImRoomChatMessageResponseDto> resDtoList = new ArrayList<>();
        if(basePage == null){
            return resDtoList;
        }
        //分页对象        PageHelper
        IPage<ImRoomChatMessage> iPage = new Page<>(basePage.getPageNo(), basePage.getRealPageSize());
        QueryWrapper<ImRoomChatMessage> queryWrapper = checkQueryCondition(basePage);

        IPage<ImRoomChatMessage> page = imRoomChatMessageDao.page(iPage, queryWrapper);
        if(null == page){
            return resDtoList;
        }

        List<ImRoomChatMessage>  list = page.getRecords();
        if(null == list || list.isEmpty()){
            return resDtoList;
        }
        list.forEach(imRoomChatMessage -> {
                ImRoomChatMessageResponseDto imRoomChatMessageResponseDto = ImRoomChatMessageResponseDto.build().clone(imRoomChatMessage);

            resDtoList.add(imRoomChatMessageResponseDto);
        });
        responseResultList.setTotal((int) page.getTotal());
        return resDtoList;


    }

    /**
     * 通过分页获取ImRoomChatMessage信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-12 17:26:21
     */
    @Override
    public ResponseResultList<ImRoomChatMessageResponseDto> getImRoomChatMessageByNextPage(BasePage basePage){
        ResponseResultList<ImRoomChatMessageResponseDto> responseResultList = ResponseResultList.build();
        List<ImRoomChatMessageResponseDto>  list = this.getImRoomChatMessageByPage(responseResultList,basePage);
        if(null == list ){
            list = new ArrayList<>();
        }
        boolean isNext =  basePage.isNextPage(list);
        responseResultList.toIsNextPage(isNext).toList(list);
        return responseResultList;

    }
    /**
     * 通过分页获取ImRoomChatMessage信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-12 17:26:21
     */
    @Override
    public ResponseResultList<ImRoomChatMessageResponseDto> getImRoomChatMessageByRoomIdPage(BasePage basePage){

        List<ImRoomChatMessageResponseDto>  list = imRoomChatMessageDao.getImRoomChatMessageByRoomIdPage(basePage);

        if(null == list ){
            list = new ArrayList<>();
        }
        //todo 查用 ImMessageReadDao表,对应群已读到的消息下标
        ImRoomChatMessageRequestDto imRoomChat = (ImRoomChatMessageRequestDto)basePage.getParamObject();
        ImMessageReadRequestDto im = ImMessageReadRequestDto.build().toUserId(imRoomChat.getSendUserId())
                .toMessageId(imRoomChat.getToId()).toType(ImMessageTypeEnum.Group.getKey());
        ImMessageRead read = imMessageReadDao.getImMessageReadByUser(im);
        long readMessageId = 0;
        if(read != null){
            readMessageId = read.getGlobalId();
        }
        long finalReadMessageId = readMessageId;
        list.forEach(dto ->{
            int  readStatus = 1;//默认已读状
            if(dto.getGlobalId() > finalReadMessageId){
                readStatus = 0;//未读状态
            }
            dto.setReadStatus(readStatus);
        });

        ResponseResultList<ImRoomChatMessageResponseDto> responseResultList =
                ResponseResultList.build(list,basePage.getRealPageSize());
        return responseResultList;


    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage iPage =  new Query<ImRoomChatMessage>().getPage(params);
        QueryWrapper<ImRoomChatMessage> queryWrapper = new QueryWrapper<>();
        IPage<ImRoomChatMessage> page = imRoomChatMessageDao.page(iPage,queryWrapper);
        return new PageUtils(page);
    }


    /**
     * 保存同时更新数据库和缓存的实现方法
     * @return
     */
    public ImRoomChatMessage  setImRoomChatMessage(){
        ImRoomChatMessage imRoomChatMessage = new ImRoomChatMessage();
        /**
 			//imRoomChatMessage.setSendUserId (String sendUserId);
 			//imRoomChatMessage.setSendUserName (String sendUserName);
 			//imRoomChatMessage.setSendUsrImg (String sendUsrImg);
 			//imRoomChatMessage.setSendTime (Date sendTime);
 			//imRoomChatMessage.setServiceTime (Date serviceTime);
 			//imRoomChatMessage.setMessageId (long messageId);
 			//imRoomChatMessage.setGlobalId (long globalId);
 			//imRoomChatMessage.setMessageType (int messageType);
 			//imRoomChatMessage.setContent (String content);
 			//imRoomChatMessage.setContentImg (String contentImg);
 			//imRoomChatMessage.setContentVideo (String contentVideo);
 			//imRoomChatMessage.setMine (int mine);
 			//imRoomChatMessage.setToId (String toId);
 			//imRoomChatMessage.setToUserName (String toUserName);
 			//imRoomChatMessage.setToUserImg (String toUserImg);
 			//imRoomChatMessage.setReadStatus (int readStatus);
		**/

        return imRoomChatMessage;
    }
    @Override
    public boolean saveData(InputStream initialStream) {
        return ExcelUtils.readExcel(initialStream,imRoomChatMessageDao, ImRoomChatMessage.class,0);
    }


}
